package com.hezhiqin.zk;


import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * @program: homeWork
 * @description:
 * @author: hezhiqin
 * @create: 2020-01-14 16:32
 */
public class CuratorDemo {
    public  static  final  String CONNECTION_STR ="192.168.187.10:2181,192.168.187.11:2181,192.168.187.12:2181";
    public static void main(String[] args) {
        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString(CONNECTION_STR)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000,3)).build();
        framework.start();

        //增加
//        framework.create();
        try {
            createData(framework);
//            //删除
//            framework.delete();
//            //修改
//            updateData(framework);
//            //删除
//            deleteData(framework);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private  static  void  createData(CuratorFramework framework) throws Exception {
       framework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/temp","test".getBytes());
    }


    private static void updateData(CuratorFramework curatorFramework) throws Exception {
        curatorFramework.setData().forPath("/data/program","up".getBytes());
    }


    private static void deleteData(CuratorFramework curatorFramework) throws Exception {
        Stat stat=new Stat();
        String value=new String(curatorFramework.getData().storingStatIn(stat).forPath("/data/program"));
        curatorFramework.delete().withVersion(stat.getVersion()).forPath("/data/program");
    }

}
